const { checkinApi } = require('../../../../utils/api');
const auth = require('../../../../utils/auth');
const tips = require('../../../../utils/tips');

Page({
  data: {
    mode: 'normal',
    form: {
      title: '',
      description: '',
      startTime: '',
      endTime: '',
      classId: '',
      checkinType: 'daily',
      rewardPoints: 10,
      isRequired: true,
      allowLate: false,
      latePenalty: 0
    },
    classList: [
      { id: 2504, name: '六年级一班' },
      { id: 2505, name: '六年级二班' },
      { id: 2506, name: '六年级三班' }
    ],
    selectedClass: {},
    classIndex: 0,
    submitting: false,
    canSubmit: false,
    // 打卡类型选项
    checkinTypes: [
      { value: 'daily', label: '每日打卡', desc: '每天都需要完成' },
      { value: 'weekly', label: '每周打卡', desc: '每周完成指定次数' },
      { value: 'custom', label: '自定义', desc: '灵活设置打卡规则' }
    ],
    // 时间选择器
    timePickerVisible: false,
    currentTimeField: '',
    minDate: '',
    maxDate: ''
  },

  onLoad(query) {
    if (query && query.mode) {
      this.setData({ mode: query.mode });
    }
    
    // 设置默认时间
    const now = new Date();
    const tomorrow = new Date(now.getTime() + 24 * 60 * 60 * 1000);
    const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    
    this.setData({
      minDate: this.formatDate(now),
      maxDate: this.formatDate(nextWeek),
      'form.startTime': this.formatDateTime(tomorrow),
      'form.endTime': this.formatDateTime(nextWeek)
    });
    
    this.checkFormValid();
  },

  // 输入框变化
  onInput(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({ 
      [`form.${field}`]: value 
    });
    
    this.checkFormValid();
  },

  // 班级选择
  onClassChange(e) {
    const index = e.detail.value;
    const selectedClass = this.data.classList[index];
    
    this.setData({
      classIndex: index,
      selectedClass: selectedClass,
      'form.classId': selectedClass.id
    });
    
    this.checkFormValid();
  },

  // 打卡类型选择
  onCheckinTypeChange(e) {
    const type = e.currentTarget.dataset.type;
    this.setData({
      'form.checkinType': type
    });
  },

  // 开关变化
  onSwitchChange(e) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    
    this.setData({
      [`form.${field}`]: value
    });
  },

  // 时间选择
  onTimePickerTap(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      timePickerVisible: true,
      currentTimeField: field
    });
  },

  // 时间选择器确认
  onTimePickerConfirm(e) {
    const value = e.detail.value;
    this.setData({
      [`form.${this.data.currentTimeField}`]: value,
      timePickerVisible: false
    });
    this.checkFormValid();
  },

  // 时间选择器取消
  onTimePickerCancel() {
    this.setData({
      timePickerVisible: false
    });
  },

  // 检查表单是否有效
  checkFormValid() {
    const { title, startTime, endTime, classId } = this.data.form;
    const canSubmit = title.trim() && startTime && endTime && classId;
    
    this.setData({ canSubmit });
  },

  // 提交表单
  async submit() {
    if (!this.data.canSubmit || this.data.submitting) {
      return;
    }
    
    this.setData({ submitting: true });
    
    try {
      const checkinData = {
        classId: Number(this.data.form.classId),
        creatorUserId: 10001, // TODO: 替换为实际登录老师ID
        title: this.data.form.title,
        description: this.data.form.description,
        startTime: this.data.form.startTime,
        endTime: this.data.form.endTime,
        checkinType: this.data.form.checkinType,
        rewardPoints: this.data.form.rewardPoints,
        isRequired: this.data.form.isRequired,
        allowLate: this.data.form.allowLate,
        latePenalty: this.data.form.latePenalty
      };
      
      console.log('创建打卡活动数据:', checkinData);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      wx.showToast({ 
        title: '创建成功', 
        icon: 'success',
        duration: 1500
      });
      
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      
    } catch (error) {
      console.error('创建打卡活动失败:', error);
      wx.showToast({ 
        title: '创建失败，请重试', 
        icon: 'none' 
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 保存草稿
  saveDraft() {
    const { title, description } = this.data.form;
    
    if (!title.trim() && !description.trim()) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      });
      return;
    }

    wx.showToast({
      title: '草稿保存功能开发中',
      icon: 'none'
    });
  },

  // 格式化日期
  formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 格式化日期时间
  formatDateTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  }
});







